package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MyTask implements Runnable {
    private static final String TAG = "MyTask";
    private Handler handler;


    public void setHandler(Handler handler) {

        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //获取网络数据
        List<String> rateList = new ArrayList<String>();
        try {

            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Log.i(TAG, "run: title=");
            Elements tables = doc.getElementsByTag("table");
            Element table = tables.get(1);
            Elements trs = table.getElementsByTag("tr");
            for (Element tr : trs) {
                Elements tds = tr.getElementsByTag("td");
                if (tds.size() > 0) {
                    String td1 = tds.get(0).text();
                    String td2 = tds.get(5).text();
                    Log.i(TAG, "run: " + td1 + "-->" + td2);
                    rateList.add(td1 + "-->" + td2);

                }
            }

            Message msg = handler.obtainMessage(5, rateList);
            //    msg.what = 7;
            //    msg.obj = "hello from msg";
            handler.sendMessage(msg);
            Log.i(TAG, "run: sendMessage OK");


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}